<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
    <template v-slot:can="{row}">
      <ul class="flex">
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>私有：</span><radio_switch name="private" v-model:value="row.value.private"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>添加：</span><radio_switch name="can_add" v-model:value="row.value.can_add"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>编辑：</span><radio_switch name="can_edit" v-model:value="row.value.can_edit"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>详情：</span><radio_switch name="can_info" v-model:value="row.value.can_info"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>列表-后台：</span><radio_switch name="can_list" v-model:value="row.value.can_list"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>列表-前端：</span><radio_switch name="can_home_list" v-model:value="row.value.can_home_list"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>发货-详情：</span><radio_switch name="can_deliver_info" v-model:value="row.value.can_deliver_info"></radio_switch></li>
        <li class="flex" style="align-items: center;margin-right: 20px;"><span>发货-编辑：</span><radio_switch name="can_deliver" v-model:value="row.value.can_deliver"></radio_switch></li>
      </ul>
    </template>
    <template v-slot:hr="{row}">
      ---------------------------{{row.value}}---------------------------
    </template>
  </forms>
</template>

<script>
export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let model_id = this.$get('model_id');

    let table_map = this.admin_config('status_alias_map.model_field.table');
    let type_map = this.field_type(this.field_type.CAN_MODEL_FIELD, 'label');
    let type_config = {
      varchar: '可变长度字符',
      text: '长字符(0-65535)',
      time: '时间',
      date: '日期',
      datetime: '时间日期(1000-9999)',
      timestamp: '时间日期(1970-2038)',
      tinyint: '整数(0-255)',
      smallint: '整数(0-6万)',
      int: '整数(0-42亿)',
      decimal: '小数(0-99,999,999.99)',
    }
    let list_props_config = {
      min_width: {label:'最小宽度',name:'min_width',type:'text_one',tips:'建议单位：px。1rem=100px'},
      align: {label:'对齐方式',name:'align',type:'text_one',tips:'left、center、right 。默认为 center'},
    }
    let forms_config = {
      model_id: {label:'模型',name:'model_id',type:'select_one',config:[],tips:'',value: model_id||''},
      table: {label:'所属表',name:'table',type:'select_one',config:table_map,value:0},
      name: {label:'字段名',name:'name',type:'text_one',tips:'字段名，关联字段用{table}.{field}，例如category.name，字段格式不能更改'},
      label: {label:'别名',name:'label',type:'text_one',tips:''},
      tips: {label:'提示',name:'tips',type:'text_one',tips:'字段注释、提示'},
      can: {label:'操作权限',name:'can',type:'can',tips:'指定字段是否可以添加、编辑；是否可以在列表接口获取', value:{private:0,can_add:0,can_edit:0,can_info:1,can_list:0,can_home_list:0,can_deliver_info:0,can_deliver:0}},
      list_props: {label:'列表样式',name:'list_props',type:'json_param',config:list_props_config,tips:''},
      type: {label:'输入类型',name:'type',type:'select_one',config:type_map,tips:'选择输入的组件类型',value:''},
      config: {label:'组件配置',name:'config',type:'text_more',tips:''},
      value: {label:'组件默认值',name:'value',type:'text_one',tips:'默认值'},
      validate: {label:'验证规则',name:'validate',type:'text_one',tips:'数组json字符串，常用规则：nullable（可以为空）required（必填）numeric（数值）regex:pattern（按pattern正则表达式验证）。<a target="_blank" href="https://learnku.com/docs/laravel/9.x/validation/12219#189a36">参考文档</a>', value:'[]'},
      sort: {label:'排序',name:'sort',type:'text_one',config:'number',tips:'排序索引，大>小', value:100},
      hr: {label:'分割线',type:'hr',tips:'',value:'以下为字段数据库配置',remove:true},
      mysql_type: {label:'字段类型',name:'mysql_type',type:'select_one',config:type_config,tips:'字段mysql类型',value:'varchar',remove:true},
      mysql_length: {label:'长度',name:'mysql_length',type:'text_one',config:'number',tips:'varchar类型字段的长度限制',value:'255'},
      default: {label:'默认值',name:'default',type:'text_one',tips:'字段mysql默认值，为null表示该字段可以为null',remove:true},
      unsigned: {label:'无符号',name:'unsigned',type:'radio_switch',tips:'字段mysql类型无符号',value:1,remove:true},
    }
    if (id){
      forms_config.model_id.is_info = true;
      forms_config.table.is_info = true;
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      btns = [];
    }
    return {
      id: id,
      model_id: model_id,
      btns: btns,
      config: forms_config,
      is_default: 0,
      name_has_point: false,
    }
  },
  methods: {
    param(data){
      data = data || {};
      data.model_id = this.model_id;
      return s94Mjs.param_encode(data);
    },
    onsubmit(formData){
      let url = this.id ? `/admin/model_field/edit?id=`+this.id : '/admin/model_field/add';
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('index', '$refs.list_url.list');
          iframe.exe('/model/all?id='+this.model_id, 'model_field_list');
          iframe.hide('edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })
    },
    remove_option(name, type){
      let has_point = name && ~name.indexOf('.');
      this.config.hr.remove=
          this.config.validate.remove=
              this.config.mysql_type.remove=
                  this.config.default.remove=
                      this.config.unsigned.remove=has_point;
      if (!has_point) {
        let is_num = ~(['tinyint','smallint','int','decimal']).indexOf(type);
        this.config.default.config = is_num ? 'number' : '';
        this.config.unsigned.remove = !is_num;
      }
    },
  },
  watch: {
    'config.name.value'(v, oldV){
      if (this.id){
        if (!oldV) return;
        if (!!~v.indexOf('.') !== this.name_has_point) {
          this.$refs['forms'].errors['name'] = '字段格式不能更改';
        }else {
          this.$refs['forms'].errors['name'] = '';
        }
      }else {
        this.remove_option(v, this.config.mysql_type.value);
      }
    },
    'config.mysql_type.value'(v){
      this.remove_option(this.config.name.value, v);
      this.config.mysql_length.remove = v!='varchar';
    },
    'config.type.value'(v){
      s94Mjs.each(field_type.component_config(v), (v,k)=>{
        this.config.config[k] = v;
      })
    }
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/model_field/info?id='+this.id, cache:true}, (res)=>{
        app.is_default = res.data['is_default'];
        app.name_has_point = !!~res.data.name.indexOf('.');
        if (app.is_default==1){
          app.config.name.type = '';
          app.config.name.tips = '默认字段，字段名不能更改！';
        }
        res.data.can = {
          private: res.data.private,
          can_add: res.data.can_add,
          can_edit: res.data.can_edit,
          can_info: res.data.can_info,
          can_list: res.data.can_list,
          can_home_list: res.data.can_home_list,
          can_deliver_info: res.data.can_deliver_info,
          can_deliver: res.data.can_deliver,
        }
        app.$refs['forms'].init(res.data);
        app.remove_option(res.data.name, res.data.mysql_type);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('edit');
        }else {
          this.$router.push('index');
        }
      })
    }else {
      app.remove_option(this.config.name.value, this.config.mysql_type.value);
      this.config.type.value = 'text_one';
    }

    //其他初始化操作
    ajax({url:'/admin/index/model_list',cache:true},function(res){
      app.config.model_id.config = app.decode_config(res.data.list, {content_key:'alias', value_key:'id'});
      return false
    })
  }
}
</script>
